//
//  WeiboDetailViewController.m
//  微blog
//
//  Created by Jorn.Wu on 15/8/28.
//  Copyright (c) 2015年 Jorn.Wu(jorn_wza@sina.com). All rights reserved.
//

#import "WeiboDetailViewController.h"
#import "WeiboView.h"
#import "ThemeImageView.h"
#import "ThemeLabel.h"
#import "HomeWeiboModel.h"
#import "UIImageView+WebCache.h"
#import "NSDateUtils.h"
#import "UserModel.h"
#import "UIViewExt.h"
#import "SinaWeibo.h"
#import "AppDelegate.h"
#import "WeiboDetailTableView.h"
#import "WeiboCommentModel.h"
#import "MJRefresh.h"

@interface WeiboDetailViewController ()<SinaWeiboDelegate,SinaWeiboRequestDelegate>

/**
 * weibo视图
 */
@property (nonatomic, strong) WeiboView *weiboView;

/**
 * 用户头像
 */
@property (strong, nonatomic) UIImageView *userIcon;

/**
 * 用户昵称
 */
@property (strong, nonatomic) ThemeLabel *userName;

/**
 * 微薄来源
 */
@property (strong, nonatomic) ThemeLabel *source;

/**
 * 创建时间
 */
@property (strong, nonatomic) ThemeLabel *createDate;

/**
 * 转发次数
 */
@property (strong, nonatomic) ThemeLabel *repostsCount;

/**
 * 评论次数
 */
@property (strong, nonatomic) ThemeLabel *commentsCount;

/**
 * 点赞次数
 */
@property (strong, nonatomic) ThemeLabel *attitudesCount;

/**
 * 评论列表
 */
@property (nonatomic, strong) WeiboDetailTableView *detailTableView;

/**
 * 顶部视图
 */
@property (nonatomic, strong) UIView *topView;

/**
 * 微博对象
 */
@property (nonatomic, strong) SinaWeibo *sinaWeibo;

/**
 * 用于存储模型
 */
@property (nonatomic, strong) NSMutableArray *commentModelAr;

/**
 * 用于装载请求的新数据
 */
@property (nonatomic, strong) NSMutableArray *dataAr;

@end

@implementation WeiboDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

///--------------------------------------网络请求------------------------------------------------------
#pragma mark - 网络请求

/**
 * 获取weibo对象
 */
- (SinaWeibo *)sinaweibo
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaweibo;
}

/**
 * 加载数据
 */
- (void)loadWeiboCommentData{
    
    NSString *weiboId = [self.weiboFrameModel.weiboModel.weiboId stringValue];
    _sinaWeibo = [self sinaweibo];
    
    if ([_sinaWeibo isAuthValid]) {
        //        kSinaWeiboLog(@"已经登录");
        NSDictionary *params = @{
                                 @"count" : @"10",
                                 @"id" : weiboId
                                 };
        
        //获取评论
        SinaWeiboRequest *request = [_sinaWeibo requestWithURL:comments
                                                    params:[params mutableCopy]
                                                httpMethod:@"GET"
                                                  delegate:self];
        request.tag = 100;      //默认值
    }else{
        
        [_sinaWeibo logIn];
    }
    
}

///---------- 懒加载数组 ---------

- (NSMutableArray *)dataAr{
    if (!_dataAr) {
        _dataAr = [NSMutableArray array];
    }
    return _dataAr;
}

- (NSMutableArray *)commentModelAr{
    if (!_commentModelAr) {
        _commentModelAr = [NSMutableArray array];
    }
    return _commentModelAr;
}


#pragma mark 微博请求代理

/**
 * 请求状态
 */

//1.网络请求失败
- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error {
    kSinaWeiboLog(@"网络接口请求失败：%@",error);
}


//2 网络请求成功
- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result{
    
//    NSLog(@"%@",result);
    
    NSArray *commentAr = [result objectForKey:@"comments"];

    NSMutableArray *tCommentModelArray = [[NSMutableArray alloc] initWithCapacity:commentAr.count];
    
    for (NSDictionary *commentDic in commentAr) {      //每条评论
        WeiboCommentModel *model = [[WeiboCommentModel alloc] initWithDataDic:commentDic];
        [tCommentModelArray addObject:model];
        
    }
    
    self.dataAr = [tCommentModelArray mutableCopy];       //一定是mutableCopy，否则dataAr将转会为不可变，后面不可增删等操作了
    
    /**
     * 对获取数据进行处理
     */
    if (request.tag == 100) {       //第一次请求
        
        self.commentModelAr = [self.dataAr mutableCopy];      //一定是mutableCopy，否则commentModelAr将转会文不可变，后面不可增删等操作了
        //把modelArray数据传到tableView显示出来
        if (self.dataAr.count > 0) {        //有数据
            _detailTableView.weiboCommentModelAr = [self.commentModelAr copy];
            [_detailTableView reloadData];
        }

    }else if (request.tag == 101) {     //下拉刷新
        
        if (self.dataAr.count > 1) {
//                        kSinaWeiboLog(@"xia---%li",self.dataAr.count);
            
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.dataAr.count)];
            [self.commentModelAr insertObjects:self.dataAr atIndexes:indexSet];
            _detailTableView.weiboCommentModelAr = [self.commentModelAr copy];
            [_detailTableView reloadData];
            
        }

    }else if (request.tag == 102) {     //上拉加载
        
        if (self.dataAr.count > 1) {
//                        kSinaWeiboLog(@"shang---%li",self.dataAr.count);
            
            [self.dataAr removeObjectAtIndex:0];        //去掉重复的第一个
            [self.commentModelAr addObjectsFromArray:self.dataAr];
            _detailTableView.weiboCommentModelAr = [self.commentModelAr copy];
            [_detailTableView reloadData];
        }

    }

    [self.detailTableView.header endRefreshing];
    [self.detailTableView.footer endRefreshing];
    
}















///-------------------------------------界面的搭建----------------------------------------------------------
#pragma mark - 界面搭建

/**
 * 第一个调用的方法，保证正在数据传入之前创建好各个视图
 */
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
                
        /**
         * 必须先创建相关控件，否则赋值失败
         */
        [self addTopView];
        
        /**
         * 添加列表
         */
        [self addDetailTableView];
    
        
    }
    return self;
}


/**
 * 创建头部各控件
 */
- (void)addTopView{
    
    _topView = [[UIView alloc] initWithFrame:CGRectZero];
    _topView.backgroundColor = [UIColor clearColor];
    
    _userIcon = [[UIImageView alloc] initWithFrame:CGRectZero];
    
    _userName = [[ThemeLabel alloc] initWithFrame:CGRectZero];
    _userName.font = [UIFont systemFontOfSize:17];
    
    _createDate = [[ThemeLabel alloc] initWithFrame:CGRectZero];
    _createDate.font = [UIFont systemFontOfSize:13];
    
    _source = [[ThemeLabel alloc] initWithFrame:CGRectZero];
    _source.font = [UIFont systemFontOfSize:13];
    
    _repostsCount = [[ThemeLabel alloc] initWithFrame:CGRectZero];
    _repostsCount.font = [UIFont systemFontOfSize:15];
    
    _commentsCount = [[ThemeLabel alloc] initWithFrame:CGRectZero];
    _commentsCount.font = [UIFont systemFontOfSize:15];
    
    _attitudesCount = [[ThemeLabel alloc] initWithFrame:CGRectZero];
    _attitudesCount.font = [UIFont systemFontOfSize:15];;
    
    [self.topView addSubview:_userIcon];
    [self.topView addSubview:_userName];
    [self.topView addSubview:_createDate];
    [self.topView addSubview:_source];
    [self.topView addSubview:_repostsCount];
    [self.topView addSubview:_commentsCount];
    [self.topView addSubview:_attitudesCount];
    
}



/**
 * 懒加载创建微博视图
 */
- (WeiboView *)weiboView{
    if (!_weiboView) {
        _weiboView = [[WeiboView alloc] initWithFrame:CGRectZero];
        [self.topView addSubview:_weiboView];
    }
    return _weiboView;
}



/**
 * 赋值是调用
 */
- (void)setWeiboFrameModel:(HomeWeiboFrameModel *)weiboFrameModel{
    
    _weiboFrameModel = weiboFrameModel;
    
    /**
     * 加载评论列表信息
     */
    [self loadWeiboCommentData];
    
    
    
    self.weiboView.weiboFrameModel = _weiboFrameModel;
    
    /**
     * 获取frame中对应的model
     */
    HomeWeiboModel *weiboModel = self.weiboFrameModel.weiboModel;
    
    
    /**
     * 将各参数显示
     */
    self.createDate.text = [NSString stringWithFormat:@"时间:%@",[NSDateUtils weiboDateString:weiboModel.createDate]];         //通过工具类转化
    self.createDate.textColorName = @"Timeline_Time_color";     //使用主题颜色
    
    self.source.text = weiboModel.source;
    self.source.textColorName = @"Timeline_Time_color";
    
    self.repostsCount.text = [NSString stringWithFormat:@"转发:%d",[weiboModel.repostsCount intValue]];
    self.commentsCount.text = [NSString stringWithFormat:@"评论:%d",[weiboModel.commentsCount intValue]];
    self.attitudesCount.text = [NSString stringWithFormat:@"赞:%d",[weiboModel.attitudesCount intValue]];
    
    self.repostsCount.textColorName = @"Timeline_Name_color";
    self.commentsCount.textColorName = @"Timeline_Name_color";
    self.attitudesCount.textColorName =@"Timeline_Name_color";
    
    NSString *urlStr = weiboModel.userModel.profile_image_url;
    [self.userIcon sd_setImageWithURL:[NSURL URLWithString:urlStr]];
    
    self.userName.text = weiboModel.userModel.screen_name;
    

}


/**
 * 添加列表
 */
- (void)addDetailTableView{
    
    _detailTableView = [[WeiboDetailTableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
    
    self.detailTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshNewData)];
    self.detailTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [self.view addSubview:_detailTableView];
    
}

/**
 * 下拉刷新
 */
- (void)refreshNewData{
//        kSinaWeiboLog(@"正在刷新");
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@"10" forKey:@"count"];
    
    NSString *weiboId = [self.weiboFrameModel.weiboModel.weiboId stringValue];
    [params setObject:weiboId forKey:@"id"];
    
    if (self.commentModelAr.count > 1) {//有评论显示了。
        
        WeiboCommentModel *weiboCommentModel = self.commentModelAr[0];     //目前最新的微博评论
        NSString *sinceId = weiboCommentModel.idstr;
        [params setObject:sinceId forKey:@"since_id"];
        
    }
    
    //获取微博
    SinaWeiboRequest *request = [_sinaWeibo requestWithURL:comments
                                                    params:[params mutableCopy]
                                                httpMethod:@"GET"
                                                  delegate:self];
    
    request.tag = 101;      //刷新的request标识
}


/**
 * 上拉加载
 */
- (void)loadMoreData{
//        kSinaWeiboLog(@"正在加载");
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@"10" forKey:@"count"];
    
    NSString *weiboId = [self.weiboFrameModel.weiboModel.weiboId stringValue];
    [params setObject:weiboId forKey:@"id"];
    
    WeiboCommentModel *weiboCommentModel = [self.commentModelAr lastObject];     //目前最下面
    NSString *maxId = weiboCommentModel.idstr;
    [params setObject:maxId forKey:@"max_id"];
    
    //获取微博
    SinaWeiboRequest *request = [_sinaWeibo requestWithURL:comments
                                                    params:[params mutableCopy]
                                                httpMethod:@"GET"
                                                  delegate:self];
    
    request.tag = 102;      //加载的request标识
}



/**
 * 根据内容布局子视图
 */
- (void)viewWillLayoutSubviews{
    
    /* 1> icon,name,date,source */
    
    CGFloat spaceing1 = 10;         //间距
    
    _userIcon.frame = CGRectMake(spaceing1, spaceing1, 70, 70);
    
    _userName.frame = CGRectMake(CGRectGetMaxX(_userIcon.frame) + spaceing1,
                                 spaceing1 + 2,
                                 kScreenWidth - CGRectGetWidth(_userIcon.frame) - 30 - 40,
                                 30);     //40 是尾部预留空间
    
    _createDate.frame = CGRectMake(CGRectGetMaxX(_userIcon.frame) + spaceing1,
                                   CGRectGetMaxY(_userName.frame) + spaceing1,
                                   (kScreenWidth - CGRectGetMaxX(_userIcon.frame) - 20) / 2.0,
                                   20);
    
    _source.frame = CGRectMake(CGRectGetMaxX(_createDate.frame) + spaceing1,
                               CGRectGetMaxY(_userName.frame) + spaceing1,
                               CGRectGetWidth(_createDate.frame),
                               20);
    
    /* 2> weiboView */
    
    CGRect frame = self.weiboFrameModel.frame;
    CGFloat y = CGRectGetMaxY(_userIcon.frame) + 10;
    frame = CGRectMake(self.weiboFrameModel.frame.origin.x,
                       y,
                       CGRectGetWidth(self.weiboFrameModel.frame),
                       CGRectGetHeight(self.weiboFrameModel.frame));

    self.weiboView.frame = frame;
    
    
    /* 3> _repostsCount,_commentsCount,_attitudesCount */
    
    CGFloat spacing2 = (kScreenWidth - 70 * 3) / 4.0;        //间距
    
    _repostsCount.frame = CGRectMake(spacing2,
                                     CGRectGetMaxY(_weiboView.frame),
                                     70,
                                     30);
    
    _commentsCount.frame = CGRectMake(CGRectGetMaxX(_repostsCount.frame) + spacing2,
                                      _repostsCount.frame.origin.y,
                                      70,
                                      30);
    
    _attitudesCount.frame = CGRectMake(CGRectGetMaxX(_commentsCount.frame) + spacing2,
                                      _repostsCount.frame.origin.y,
                                      70,
                                      30);
    
    /**
     * 最终获得topView的frame
     */
    _topView.frame = CGRectMake(0, 0, kScreenWidth, CGRectGetMaxY(_repostsCount.frame) + 10);
    
    /**
     * 将topView作为table的头部视图
     */
    _detailTableView.tableHeaderView = self.topView;
    

    
}



///---------------------------------------------------------------------------------------------------











- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
